package gestioneDatabase;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * Classe che permette di agire sui file XML.
 * 
 */
public class XMLController {

	private DocumentBuilderFactory factory;
	private DocumentBuilder builder;
	private Document doc;

	public XMLController(DocumentBuilderFactory factory,
			DocumentBuilder builder, Document doc) {
		super();
		this.factory = factory;
		this.builder = builder;
		this.doc = doc;
	}

	/**
	 * Apre il file XML dato.
	 * 
	 * @param filepath
	 *            Il percorso del file XML.
	 * 
	 * @return doc Il documento XML richiesto.
	 * 
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */

	public Document openXMLFile(String filepath)
			throws ParserConfigurationException, SAXException, IOException {
		factory = DocumentBuilderFactory.newInstance();
		builder = factory.newDocumentBuilder();
		doc = builder.parse(new File(filepath));
		return doc;
	}

	/**
	 * Metodo che permette di scrivere su un file XML.
	 * 
	 * @param filepath
	 *            Il percorso del file XML.
	 * 
	 * @throws TransformerFactoryConfigurationError
	 * @throws TransformerConfigurationException
	 * @throws TransformerException
	 */
	public void writeIntoXMLFile(String filepath)
			throws TransformerFactoryConfigurationError,
			TransformerConfigurationException, TransformerException {
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File(filepath));
		transformer.transform(source, result);
	}

}
